package com.realtyManage.springboot.Service.authImpl;

import com.realtyManage.springboot.Dao.UserRepository;
import com.realtyManage.springboot.Model.Do.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 杭州素色网络科技有限公司
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserRepository userRepository;

    /**
     * 通过构造器注入UserRepository
     * @param userRepository
     */
    public UserDetailsServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByTelephone(username);
        if(user == null){
            throw new UsernameNotFoundException(username);
        }
        String[] roles = user.getLevel().toString().split(",");
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        for(String role : roles)
        {
            authorities.add(new SimpleGrantedAuthority(role));
        }

        return new org.springframework.security.core.userdetails.User(user.getTelephone(), user.getPwd(), authorities);
    }

}
